//
//  ViewController.m
//  Block
//
//  Created by Mac on 16/5/22.
//  Copyright (c) 2016年 liuhai. All rights reserved.
//

#import "ViewController.h"
#import <QuartzCore/QuartzCore.h>


@interface ViewController ()
{
    //  游戏开始的标识
    BOOL _isPlaying;
    
    //   小球的速度
    CGPoint _ballVelovcity;
    
    //  游戏时钟
    CADisplayLink *_gameTimer;
    
    //  水平位移
    CGFloat _deltaX;
}

/**
 * 时钟触发方法
 * @param
 * @return
 */
- (void)step:(CADisplayLink *)sender;

/**
 * 检测与屏幕的碰撞
 * @param
 * @return boolean
 */
- (BOOL)checkWithScreen;

/**
 * 检测与砖块的碰撞
 * @param
 * @return boolean
 */
- (BOOL)checkWithBlocks;

/**
 * 检测与挡板的碰撞
 * @param
 * @return
 */
- (void)checkWithPaddle;

/**
 * 重置游戏状态，胜利或者失败
 * @param
 * @return
 */
- (void)resetGameStatusWithMessage : (NSString *)message;

@end

@implementation ViewController


- (void)resetGameStatusWithMessage:(NSString *)message
{
    NSLog(@"%@",message);
    
    // 关闭游戏时钟
    [_gameTimer invalidate];
    // 将所有的砖头设置成可见
    for (UIImageView *block in _blockImages)
    {
        [block setHidden:NO];
        // 将透明度设置为0
        [block setAlpha:0];
        
        // 将砖头缩小
        [block setFrame:CGRectMake(block.center.x, block.center.y, NO, NO)];
    }
    
    [UIView animateWithDuration:2.0  animations:
     ^{
         for (UIImageView *block in _blockImages)
         {
             [block setHidden:NO];
             // 将透明度设置为0
             [block setAlpha:1];
             
             // 将砖头放大
             [block setFrame:CGRectMake(block.center.x - 50, block.center.y-15,
                                        100, 30)];
         }
     } completion:^(BOOL finished) {
         // 重置游戏
         _isPlaying = NO;
         // 重置后小球位置
         [_ballImage setCenter:CGPointMake(200, 560)];
         // 重置后挡板位置
         [_paddleImage setCenter:CGPointMake(200, 580)];
     }];
}

// 屏幕碰撞检测
- (BOOL)checkWithScreen
{
    BOOL gameOver = NO;
    // 左边
    if ([_ballImage frame].origin.x <= 0)
    {
        _ballVelovcity.x = fabs(_ballVelovcity.x);
    }
    
    // 右边
    if ([_ballImage frame].origin.x + [_ballImage frame].size.width
                                                >= self.view.frame.size.width)
    {
        _ballVelovcity.x = -1 * fabs(_ballVelovcity.x);
    }
    
    // 顶部
    if ([_ballImage frame].origin.y <= 0)
    {
        _ballVelovcity.y = fabs(_ballVelovcity.y);
    }
    
    // 底部
    if ([_ballImage frame].origin.y + [_ballImage frame].size.height
                                                >= self.view.frame.size.height)
    {
        gameOver = YES;
    }
    return gameOver;
}

// 砖块碰撞检测
- (BOOL)checkWithBlocks
{
    for (UIImageView *block in _blockImages)
    {
        // 如果与装快碰撞 就隐藏砖块
        if (CGRectIntersectsRect([block frame], [_ballImage frame])
            && ![block isHidden])
        {
            [block setHidden:YES];
            _ballVelovcity.y = fabs(_ballVelovcity.y);
            break;
        }
    }
    
    // 判断游戏胜利
    BOOL gameWin = YES;
    for (UIImageView *block in _blockImages)
    {
        if (![block isHidden])
        {
            gameWin = NO;
            break;
        }
    }
    /*
    int count = 0;
    for (UIImageView *block in _blockImages)
    {
        if ([block isHidden])
        {
            count ++;
        }
    }
    
    if (count == [_blockImages count] - 1)
    {
        gameWin = YES;
    }
     */
    return gameWin;
}

//    挡板碰撞检测
- (void)checkWithPaddle
{
    if (CGRectIntersectsRect([_ballImage frame], [_paddleImage frame]))
    {
        _ballVelovcity.y = -1 * fabs(_ballVelovcity.y);
        _ballVelovcity.x += _deltaX;
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// 时钟处理方法
- (void)step:(CADisplayLink *)sender
{
    // 检测屏幕碰撞
    if ([self checkWithScreen])
    {
        [self resetGameStatusWithMessage:@"再来一次吧!"];
    }
    
    // 与砖块碰撞检测
    if ([self checkWithBlocks])
    {
        [self resetGameStatusWithMessage:@"你胜利了!"];
    }
    
    // 与挡板碰撞检测
    [self checkWithPaddle];
    
    // 让小球动起来
    [_ballImage setCenter:CGPointMake(_ballImage.center.x + _ballVelovcity.x,
                                      _ballImage.center.y + _ballVelovcity.y)];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (!_isPlaying)
    {
        //分段式编程 尽早返回
        return;
    }
    
    UITouch *touch = [touches anyObject];
    // 计算手指在水平方向的移动距离
    _deltaX = [touch locationInView:self.view].x -
    [touch previousLocationInView:self.view].x;
    // 修改挡板位置
    [_paddleImage setCenter:CGPointMake([_paddleImage center].x + _deltaX,
                                        [_paddleImage center].y)];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    // 如果游戏还没有开始
    if (_isPlaying)
    {
        //分段式编程 尽早返回
        _deltaX = 0;
        return;
    }
    
    // 小球的初始状态
    _ballVelovcity = CGPointMake(0, -5);
    // 定义时钟
    _gameTimer = [CADisplayLink displayLinkWithTarget :
                  self selector : @selector(step:)];
    //  将当前时钟添加到应用循环
    [_gameTimer addToRunLoop:[NSRunLoop currentRunLoop] forMode : NSDefaultRunLoopMode];
    
    // 修改游戏状态标识
    _isPlaying = YES;
}

@end
